﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.MediaCenter.UI;
using System.Diagnostics;
using MyMoviesBrowserLibrary;

namespace MyMoviesBrowser
{
    public class TrailerGallery : GalleryPage
    {
        private Trailer currentTrailer;
        public Trailer CurrentTrailer
        {
            get { return currentTrailer; }
            set
            {
                if (currentTrailer != value)
                {
                    currentTrailer = value;
                    FirePropertyChanged("CurrentTrailer");
                }
            }
        }

        ModelItem currentFilter;

        List<Trailer> Trailers = new List<Trailer>();

        public TrailerGallery(List<Trailer> movieTrailersList)
        {
            ItemSize = GalleryItemSize.Large;
            Description = "Trailers";

            Trailers = movieTrailersList;
            //foreach (MovieTrailer mt in movieTrailersList)
            //{
            //    Trailers.Add(new Trailer(mt));
            //}

            VirtualList galleryList = new VirtualList(this, null);
            galleryList.EnableSlowDataRequests = true;
            galleryList.RequestSlowDataHandler = new RequestSlowDataHandler(CompleteGalleryItem);
            Content = galleryList;

            CreateGalleryFilters();
        }

        private void CreateGalleryFilters()
        {
            //
            // Put together a list of filters on the content.
            //

            ArrayListDataSet list = new ArrayListDataSet(this);

            // Create the unfiltered "All" filter
            ModelItem filter = new Filter(this, Resources.GroupBy_Title, 0);
            list.Add(filter);

            filter = new Filter(this, Resources.GroupBy_Newest, 1);
            list.Add(filter);

            filter = new Filter(this, Resources.FilterBy_NotWatched, 2);
            list.Add(filter);            

            filter = new Filter(this, Resources.GroupBy_MPAARating, 4);
            list.Add(filter);

            filter = new Filter(this, Resources.GroupBy_Genre, 5);
            list.Add(filter);

            filter = new Filter(this, Resources.GroupBy_Studio, 6);
            list.Add(filter);

            filter = new Filter(this, Resources.GroupBy_Release_Date, 3);
            list.Add(filter);

            filter = new Filter(this, Resources.PlayRandom, 7);
            list.Add(filter);

            //filter = new Filter(this, Resources.GroupBy_Studio,4);
            //list.Add(filter);


            //filter = new Filter(this, Resources.FilterBy_Watched, 6);
            //list.Add(filter);

            Choice filters = new Choice(this, null, list);
            filters.Chosen = (ModelItem)list[1];

            //
            // Hook up the "filter changed" event so that we can apply the
            // active filter to our gallery.
            //
            // As soon as this Filters list is set, we will get an OnActiveFilterChanged
            // event which will cause us to populate the gallery.
            //

            ActiveFilterChanged += delegate(object sender, EventArgs e)
            {
                TrailerGallery galleryPage = (TrailerGallery)sender;
                Filter activeFilter = (Filter)galleryPage.Filters.Chosen;
                FilterContent(galleryPage, activeFilter.FilterId);
            };
            Filters = filters;
        }

        private void FilterContent(TrailerGallery page, int filterId)
        {
            if (filterId != 7)
            {
                currentFilter = (ModelItem)Filters.Options[filterId];
                Content.Clear();
            }


            //
            // Populate the list with items according to the filter.
            //
            //List<MyMovie> temp = null;
            switch (filterId)
            {
                case 1:
                    var r2 = Trailers.OrderByDescending(m => m.MovieTrailer.PostDate.Value.Date).ThenBy(m => m.MovieTrailer.Title).GroupBy(m => m.MovieTrailer.PostDate.Value.Date);
                        
                    foreach (var result in r2)
                    {
                        bool first = true;
                        foreach (var m in result)
                        {
                            page.Content.Add(CreateGalleryItem(m, m.MovieTrailer.PostDate.HasValue ? m.MovieTrailer.PostDate.Value.ToString("MMM d, yyyy") : "", first));
                            first = false;
                        }
                    }
                    break;
                case 2:
                    var r3 = Trailers.Where(m => !m.MovieTrailer.Watched).OrderBy(m => m.MovieTrailer.Title);
                    foreach (Trailer m in r3)
                        page.Content.Add(CreateGalleryItem(m, "", false));
                    break;
                case 3:
                    var q = Trailers.Where(m => !m.MovieTrailer.ReleaseDate.HasValue).OrderBy(m => m.MovieTrailer.Title);
                    foreach (var m in q)
                        page.Content.Add(CreateGalleryItem(m, "", false));

                    var r4 = Trailers.Where(m => m.MovieTrailer.ReleaseDate.HasValue).OrderBy(m => m.MovieTrailer.ReleaseDate.Value.Date).ThenBy(m => m.MovieTrailer.Title).GroupBy(t => t.MovieTrailer.ReleaseDate.Value.Date);
                    foreach (var result in r4)
                    {
                        bool first = true;
                        foreach (var m in result)
                        {
                            page.Content.Add(CreateGalleryItem(m, m.MovieTrailer.ReleaseDate.HasValue ? m.MovieTrailer.ReleaseDate.Value.ToString("MMM d, yyyy") : "", first));
                            first = false;
                        }
                    }
                    break;
                case 4:
                    var r5 = Trailers.OrderBy(m => m.MovieTrailer.Rating.RatingDesc).ThenBy(m => m.MovieTrailer.Title).GroupBy(t => t.MovieTrailer.Rating.RatingDesc);
                    foreach (var result in r5)
                    {
                        bool first = true;
                        foreach (var m in result)
                        {
                            page.Content.Add(CreateGalleryItem(m, result.Key, first));
                            first = false;
                        }
                    }
                    break;
                case 5:
                    var r7 = Trailers.OrderBy(m => m.GenreString).ThenBy(m => m.MovieTrailer.Title).GroupBy(m => m.GenreString);
                    foreach (var result in r7)
                    {
                        bool first = true;
                        foreach (var m in result)
                        {
                            page.Content.Add(CreateGalleryItem(m, result.Key, first));
                            first = false;
                        }
                    }
                    break;
                case 6:
                    var r8 = Trailers.OrderBy(m => m.MovieTrailer.Studio.StudioName).ThenBy(m => m.MovieTrailer.Title).GroupBy(t => t.MovieTrailer.Studio.StudioName);
                    foreach (var result in r8)
                    {
                        bool first = true;
                        foreach (var m in result)
                        {
                            page.Content.Add(CreateGalleryItem(m, result.Key, first));
                            first = false;
                        }
                    }
                    break;
                case 7:
                    if (Trailers.Count > 0)
                    {
                        if (currentFilter != null)
                            Filters.Chosen = currentFilter;

                        Random random = new Random();
                        int index = random.Next(0, Trailers.Count);
                        Trailer trailer = Trailers[index];
                        trailer.GetFiles();
                        index = random.Next(0, trailer.Files.Count);
                        //MyMoviesBrowserBusiness.MarkTrailerAsWatched(trailer, true);
                        Application.Current.PlayMedia(trailer.Files[index], trailer);
                    }
                    break;
                default:
                    var r6 = Trailers.OrderBy(m => m.MovieTrailer.SortTitle);
                    foreach (Trailer m in r6)
                        page.Content.Add(CreateGalleryItem(m, "", false));
                    break;
            }
        }

        private ThumbnailCommand CreateGalleryItem(Trailer trailerData, string description, bool isHeading)
        {
            ThumbnailCommand item = new ThumbnailCommand(this);
            item.Description = trailerData.MovieTrailer.Title;
            item.Data = trailerData;
            item.ShowHeading = isHeading;
            item.Metadata = description;
            //
            // Hook up an event for when the gallery item is invoked.
            //

            item.Invoked += delegate(object sender, EventArgs args)
            {
                ThumbnailCommand galleryItem = (ThumbnailCommand)sender;

                Trailer movie = (Trailer)galleryItem.Data;
                //MyMoviesBrowserBusiness.MarkTrailerAsWatched(movie, true);
                //movie.Watched = true;
                Application.Current.GoToDetailsPage(movie);
            };

            item.OnFocus += delegate(object sender, EventArgs args)
            {
                ThumbnailCommand galleryItem = (ThumbnailCommand)sender;

                TrailerGallery page = (TrailerGallery)galleryItem.Owner;
                page.CurrentTrailer = (Trailer)galleryItem.Data;
            };

            return item;
        }

        public override int JumpTo(string searchText)
        {
            searchText = searchText.ToLower();
            List<Trailer> temp = Content.Cast<ThumbnailCommand>().Select(t => t.Data).Cast<Trailer>().ToList();
            List<Trailer> temp2 = new List<Trailer>();
            do
            {
                temp2 = (from m in temp
                         where m.MovieTrailer.SortTitle.ToLower().StartsWith(searchText)
                         select m).ToList();
                if (searchText.Length > 0)
                    searchText = searchText.Substring(0, searchText.Length - 1);
            } while (temp2.Count == 0 && searchText.Length > 0);

            if (temp2.Count > 0)
            {
                int i = temp.IndexOf(temp2.First());
                return i;
            }
            return -1;
        }

        #region slowdatahandlers
        /// <summary>
        /// Finishes any slow data for a gallery item.
        /// </summary>
        protected void CompleteGalleryItem(VirtualList list, int index)
        {
            ThumbnailCommand item = (ThumbnailCommand)list[index];
            CompleteGalleryItem(item, (Trailer)item.Data);
        }

        /// <summary>
        /// Finishes any slow data for a gallery item.
        /// </summary>
        protected void CompleteGalleryItem(ThumbnailCommand item, Trailer trailerData)
        {
            string imageName = "file://" + trailerData.MovieTrailer.PosterLocation;
            item.Image = LoadImage(imageName);
        }
        #endregion
    }
}
